package com.linkturing.serial;

import java.util.Enumeration;
import java.util.TooManyListenersException;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.UnsupportedCommOperationException;

public class SerialRead {
	
	static Log log = LogFactory.get();
	public static String devId = "";
	public static String port = "";
	
	public static void process() throws TooManyListenersException, NoSuchPortException {
		try {
			Enumeration portList = CommPortIdentifier.getPortIdentifiers();
			
			if(!portList.hasMoreElements()) {
				log.info("没发现串口设备！！！！");
				return;
			} 
			int deviceNum = 0;
			while (portList.hasMoreElements()) {
				
				deviceNum++;
				log.debug("串口设备NO:" + deviceNum);
				
				CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
			
//			CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier("COM1");
			
			  if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)// 如果端口类型是串口则判断名称
			  { 
				  System.out.println(portId.getName()); 
				  log.debug("open port name="+portId.getName());
				  SerialPort serialPort = (SerialPort) portId.open("Serial_Communication", 1000);// 打开串口的超时时间为1000ms
				  serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
						SerialPort.PARITY_NONE);// 设置串口速率为9600，数据位8位，停止位1们，奇偶校验无
				  serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
				  //监听串口事件
				  serialPort.addEventListener(new ReadSerialPortEventListener(serialPort,deviceNum)); //Abc是实现SerialPortEventListener接口的类，具体读操作在里面进行
				  // 设置当有数据到达时唤醒监听接收线程
				  serialPort.notifyOnDataAvailable(true);
				  // 设置当通信中断时唤醒中断线程
				  serialPort.notifyOnBreakInterrupt(true);
			  }
			 
				//    in.close(); //关闭串口
			}

		} catch (PortInUseException e) {
			e.printStackTrace();
		} catch (UnsupportedCommOperationException e) {
			e.printStackTrace();
		} 

	}

	public static void main(String[] args) throws InterruptedException, TooManyListenersException, NoSuchPortException {
		process();
	}

}
